<template>
  <div class="timedTask" id="timedTask">
    <div class="btns">
      <div class="btns_options">
        <a-button class="addButton" type="primary" :disabled="!btnPerm.includes('publishTimeTaskAble')" @click="createtaskClick(1)">
          {{ $t('content.CreateAreleaseTimingTask')
              }}
        </a-button>
        <a-button class="addButton" type="primary" :disabled="!btnPerm.includes('offineTimeTaskAble')" @click="createtaskClick(3)">
          {{ $t('content.CreateOfflineScheduledTasks')
              }}
        </a-button>
        <a-button class="addButton" type="primary" :disabled="!btnPerm.includes('topTimeTaskAble')" @click="createtaskClick(2)">
          {{ $t('content.CreateATopTimedTask')
              }}
        </a-button>
      </div>
      <div class="search_options">
        <!-- <span style="color:#333;font-size: 14px;">定时时间：</span>
        <a-range-picker v-model:value="contentTaskDate" valueFormat="YYYY-MM-DD HH:mm" :placeholder="['开始时间', '结束时间']"
          @change="onSearch" allowClear /> -->

        <span style="color:#333;font-size: 14px;">定时时间：</span>
        <date-range-picker v-model:value="contentTaskDate" :disabledInfo="disabledInfo" @change="onSearch"
          style="width:330px; margin-bottom: 16px;"></date-range-picker>

        <a-input v-model:value="contentTaskName" allow-clear placeholder="搜索定时任务名称" style="width: 150px; height:
        32px; margin-left: 12px;" @pressEnter="iptSearch" @blur="iptSearch">
          <template #suffix>
            <i class="iconfont icon-search" @click="iptSearch"></i>
          </template>
        </a-input>
      </div>
    </div>
    <div class="taskBox">
      <div v-for="(item, index) in resData.records" class="tablebox" @click="checkedClick(item.checked, index)">
        <div class="tableCont">
          <div class="tableLF">
            <div class="xwtitle">
              <a-checkbox v-model:checked="item.checked"></a-checkbox>
              <!-- <span>{{ item.xwly }}</span> -->
              <span>{{ item.name }}</span>
            </div>
            <div class="popularity"></div>
          </div>
          <div class="tableLF createbox">
            <div class="create">
              <!-- <p>
              <span>创建人：</span>
              <span>{{ item.name }}</span>
            </p> -->
              <p>
                <span>{{ item.taskType == '1' ? '定时发布时间：' : (item.taskType == '3' ? '定时下线时间：' : '定时置顶时间：') }}</span>

                <span>{{ item.executeTime }}</span>
                <!-- <span>发布时间：</span>
                <span>{{ item.executeTime }}</span> -->
              </p>
            </div>
          </div>
          <div class="tableLF">
            <div class="">
              <span class="xwtype shtype" :class="['type' + item.taskType, item.status == 2 && 'type']">{{
                getRecordValue(item.taskType) }}</span>
            </div>
            <div class="operation">
              <a class="eidtRecords" :class="{ disable: !btnPerm.includes('detailAble') }" @click.stop="check(item)" v-if="item.status == 2">查看</a>
              <a class="eidtRecords" :class="{ disable: !btnPerm.includes('editAble') }" @click.stop="check(item)" v-else>编辑</a>
              <a-popconfirm placement="topRight" :disabled="!btnPerm.includes('deleteAble')" @confirm="fetchContentTaskDelete(item)" class="eidtRecords">
                <template #title>
                  <p style="width: 197px">是否删除该定时任务，删除后不可恢复</p>
                </template>
                <a :class="{ disable: !btnPerm.includes('deleteAble') }">{{ $t('content.Delete' )}}</a>
              </a-popconfirm>
            </div>
          </div>
        </div>
      </div>
      <pagination :dataSource="resData.records" @selectAll="selectAll" @changePage="changePage" :isSelect="true"
        :selfChecked="isSelectAll" :total="resData.total" :isShowPagination="isShowPagination"
        :pageSize="params.pageSize"
        :showCheckDelete="showCheckDelete" :scroll="scroll" class="paginations" v-if='resData.records.length'>
        <template #opration>
          <a-button :style="{ 'margin-left': '8px' }" @click="deleteSelectedAll"
            :disabled="!resData.records.some((item: any) => item.checked) || !btnPerm.includes('deleteAble')">{{ $t('content.Delete' )}}</a-button>
        </template>
      </pagination>
      <a-empty v-else style="margin-top: 80px;">
        <p style="color: #b6b6b6;"> 暂无数据！</p>
      </a-empty>
    </div>

    <createTask v-if="isCreateVisible" :isVisible="isCreateVisible" :taskType="taskType" :taskId="taskId" :isEdit="isEdit" :lookOrEdit="lookOrEdit"
      :status="status" :taskOptionTitle="taskOptionTitle" @handleOk="handleOk" @handleCancle="isCreateVisible = false">
    </createTask>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick, createVNode, computed, watch } from "vue";
import pagination from "@/components/pagination/index.vue";
import { getTableScroll } from "@/components/table/tableConfig/table";
import { Modal, message } from "ant-design-vue";
import {
  scrollType,
  dataSourceType,
  detailDataType,
  configDataType,
  modeProp,
} from "@/type.d";
import request from "@/api/index";
import createTask from "./createTask.vue";
import { useRouter } from "vue-router";
import dateRangePicker from "@/components/picker/dateRangePicker.vue";
import {routerPerm} from '@/utils/common';
const btnPerm = ref<any[]>([]);
const props = defineProps({
  configData: {
    type: Object,
    default: {},
  },
});
const router = useRouter();

const contentTaskDate = ref<any>([]);
const contentTaskName = ref<string>("");
const disabledInfo = ref({
  type: 2,
  startDays: 0,
})

const options = ref(props.configData.records);
const isShowPagination = ref<boolean>(true); // 是否需要配分页器
const showCheckDelete = true; // 是否需要分页器中的自定义
const isSelectAll = ref<boolean>(false); // 是否需要配分页器
const isCreateVisible = ref<boolean>(false);
const taskId = ref();
const status = ref();
const taskOptionTitle = ref();
const isEdit = ref<boolean>(false);
const lookOrEdit = ref<boolean>(false); // 查看 false 编辑 true

const taskType = ref(1);
let rowSelection = ref<(string | number)[]>([]);
const emit = defineEmits(["changePage"]);
let resData = reactive<configDataType>({ total: 0, size: 10, records: [] });
let scroll: scrollType = reactive({ y: "", isFixed: false });
let params: dataSourceType = reactive({
  //头部筛选请求参数格式
  pageNumber: 1,
  pageSize: 10,
  createTimeStart: undefined,
  createTimeEnd: undefined,
  name: '',
});

// computed
// rowSelection = computed(() => {
//   return selectList.value;
// });
// 获取分页的改变
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  params.pageNumber = data.pageCurrent;
  params.pageSize = data.pageSize;
  fetchContentTaskPage();
};
const getRecordValue = (key: number) => {
  return key == 1
    ? "定时发布"
    : key == 2
      ? "定时置顶"
      : key == 4
        ? "取消置顶"
        : key == 3 && "定时下线";
};
nextTick(() => {
  let obj = getTableScroll(74, "contentList", 132);
  scroll.y = obj.y;
  scroll.isFixed = obj.isFixed;
});
// 查看、编辑
const check = (item: any) => {
  if(item.status == 2) {
    if(!btnPerm.value.includes('detailAble')) return
    lookOrEdit.value = false
  }else {
    if(!btnPerm.value.includes('editAble')) return
    lookOrEdit.value = true
  }
  isCreateVisible.value = true;
  taskId.value = item.id;
  isEdit.value = true;
  taskType.value = item.taskType;
  status.value = item.status;
  taskOptionTitle.value = item.status == '2' ? '查看' : '编辑';
};
// 创建定时任务
const createtaskClick = (type: any) => {
  lookOrEdit.value = true;
  taskType.value = type;
  isCreateVisible.value = true;
  isEdit.value = false;
  status.value = 1;
};
// 单选
const checkedClick = (item: any, index: number) => {
  resData.records[index].checked = !item;
  nextTick(() => {
    isSelectAll.value = resData.records.every((item: any) => item.checked == true);
  });
};

// 全选
const selectAll = (selected: [], selectedRows: [], changeRows: []) => {
  isSelectAll.value = !isSelectAll.value;
  resData.records.map((item: any) => {
    item.checked = isSelectAll.value;
  });
};
const onSearch = (data: any) => { // 条件搜索

  if (data) {
    params.createTimeStart = data[0];
    params.createTimeEnd = data[1];
  } else {
    params.createTimeStart = undefined;
    params.createTimeEnd = undefined;
  }
  fetchContentTaskPage()
};
const iptSearch = () => {
  fetchContentTaskPage()
}

// 删除
const fetchContentTaskDelete = async (data: any) => {
  let param = { ids: data.id ? [data.id] : (data || []) }
  request
    .fetchContentTaskDelete(param)
    .then((res: any) => {
      if (res.code == "00000 00000") {
        fetchContentTaskPage();
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
const deleteSelectedAll = async (item: any) => {
  Modal.confirm({
    content: "是否确定删除选中定时任务？删除后无法恢复",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "确定",
    onOk: async () => {
      let data: any[] = [];
      resData.records.forEach((item: any) => {
        if (item.checked) {
          data.push(item.id);
        }
      })
      fetchContentTaskDelete(data);
    },
    onCancel() { },
  });
};
// 获取定时任务分页数据
const fetchContentTaskPage = async (datas: dataSourceType = {}) => {
  // if (contentTaskDate.value && contentTaskDate.value.length) {
  //   params.createTimeStart = contentTaskDate.value[0] + ':00';
  //   params.createTimeEnd = contentTaskDate.value[1] + ':00'
  // }
  params.name = contentTaskName.value;
  const data = await request.fetchContentTaskPage(params);
  resData.total = data.total;
  resData.records = data.records;
  nextTick(() => {
    let obj = getTableScroll(74, "timedTask");
    scroll.y = obj.y;
    scroll.isFixed = obj.isFixed;
  });
};
const handleOk = async (item: any) => {
  isCreateVisible.value = false;
  fetchContentTaskPage();
};

// watch
watch(() => contentTaskName.value, (newVal: any, oldVal: any) => {
  if (!newVal) {
    fetchContentTaskPage()
  }

})
onMounted(() => {
  btnPerm.value = routerPerm();
  fetchContentTaskPage();
});
</script>

<style lang="less" scoped>
.timedTask {
  width: 100%;
  // min-width: 1200px;
  padding: 16px;
  background-color: #fff;
  // position: absolute;
  height: calc(100% - 72px);

  .btns {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .btns_options {
      flex: 1;
    }

    .search_options {
      width: 570px;
      display: flex;
      justify-content: end;
      line-height: 32px;
    }

    .addButton {
      margin-right: 8px;
    }

    .ant-input-search {
      margin-left: 28px;
    }
  }

  .taskBox {
    display: flex;
    flex-direction: column;
    overflow: hidden;
    height: calc(100% - 32px);
    // background: red;
    overflow-y: auto;
    position: relative;
  }

  .tablebox {
    // margin: 0 5px;
    padding: 24px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.06);
    border-radius: 2px;

    &:hover {
      margin: 0 2px;

      // background: #ffffff;

      box-shadow: 0px 5px 12px 4px rgba(0, 0, 0, 0.09),
        0px 3px 6px 0px rgba(0, 0, 0, 0.12), 0px 1px 2px -2px rgba(0, 0, 0, 0.16);
    }

    // width: 1000px;

    .imgs {
      img {
        width: 150px;
        height: 84px;
        border-radius: 2px;
        opacity: 1;
      }
    }

    .tableCont {
      flex: 1;
      margin-left: 12px;

      .tableLF {
        display: flex;
        justify-content: space-between;
        align-items: center;
        line-height: 14px;
        font-size: 14px;

        .xwtitle {
          span {
            margin-left: 6px;
            font-size: 14px;
            line-height: 14px;
          }

          span:first-child {
            color: rgba(0, 0, 0, 0.45);
          }

          span:last-child {
            color: rgba(0, 0, 0, 0.85);
            font-family: PingFang SC-Regular, PingFang SC;
            font-weight: 400;
          }
        }

        .popularity {
          font-size: 14px;
          line-height: 14px;
          color: #999;

          >span {
            margin-left: 12px;

            i {
              margin-right: 6px;
            }
          }
        }

        .xwtype {
          font-size: 12px;
          line-height: 12px;
          padding: 5px 8px;
          border-radius: 2px;
          color: #389e0d;
          background: #f6ffed;
          border: 1px solid #b7eb8f;
        }

        .type1 {
          color: #08979c;
          background: #e6fffb;
          border: 1px solid #87e8de;
        }

        .type2 {
          color: #d46b08;
          background: #fff7e6;
          border: 1px solid #ffd591;
        }

        .type3 {
          color: #cf1322;
          background: #fff1f0;
          border: 1px solid #ffa39e;
        }

        .type4 {
          color: #cf1322;
          background: #fff1f0;
          border: 1px solid #ffa39e;
        }

        .type {
          color: rgba(0, 0, 0, 0.25);
          background: rgba(0, 0, 0, 0.04);
          border: 1px solid rgba(0, 0, 0, 0.15);
        }

        .operation {
          a {
            margin-left: 16px;
          }
        }
      }

      .createbox {
        margin: 17px 0;

        .create {
          display: flex;
          font-size: 14px;

          color: rgba(0, 0, 0, 0.45);
        }
      }
    }
  }
}

.paginations {
  padding: 0 24px 16px;
  background: #fff;
  position: sticky;
  bottom: 16px;
}
</style>
